﻿using System;
using System.Diagnostics;
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TfsRollUp.Core
{
    /// <summary>
    /// A workitemstore and a fieldcollection
    /// </summary>
    public sealed class Store
    {
        /// <summary>
        /// A workitemstore
        /// </summary>
        public WorkItemStore WorkItemStore { get; set; }

        /// <summary>
        /// The workitem field collection for this store
        /// </summary>
        public WorkItemFieldCollection WorkItemFieldCollection { get; set; }

        private static WorkItemStore InternalGetStore(Uri uri)
        {
            TeamFoundationTrace.MethodEntry(uri);
            try
            {
                TeamFoundationTrace.Verbose("{0}.InternalGetStore: Creating workitemstore", Constants.TfsRollUpPlugin);
                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
                if (tfs != null)
                {
                    TeamFoundationTrace.Verbose("{0}.InternalGetStore: TfsCollection created", Constants.TfsRollUpPlugin);
                    var store = tfs.GetService<WorkItemStore>();
                    if (store == null)
                    {
                        var errorMessage = string.Format("{0}.InternalGetStore: Store not created for Uri:{1}", Constants.TfsRollUpPlugin, uri);
                        TeamFoundationApplication.Log(errorMessage, (int)Constants.EventIds.StoreNotCreated, EventLogEntryType.Warning);
                    }
                    else
                    {
                        TeamFoundationTrace.Verbose("{0}.InternalGetStore: Workitemstore created for Uri:{1}", Constants.TfsRollUpPlugin, uri);
                        TeamFoundationTrace.MethodExit();
                        return store;
                    }
                }
            }
            catch (Exception ex)
            {
                var error = string.Format("{0}.InternalGetStore:Unable to create workitemstore for Uri:'{1}'", Constants.TfsRollUpPlugin, uri);
                TeamFoundationApplication.LogException(error, ex);
            }
            TeamFoundationTrace.MethodExit();
            return null;
        }

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="uri"></param>
        public Store(Uri uri)
        {
            WorkItemStore = InternalGetStore(uri);
            WorkItemFieldCollection = new WorkItemFieldCollection(WorkItemStore);
        }

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="requestContext"></param>
        public Store(TeamFoundationRequestContext requestContext)
            : this(GetUriFromRequestContext(requestContext))
        {
        }

        /// <summary>
        /// Transform a request to a Uri
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns>Uri</returns>
        public static Uri GetUriFromRequestContext(TeamFoundationRequestContext requestContext)
        {
            TeamFoundationTrace.MethodEntry(requestContext);
            var locationService = requestContext.GetService<TeamFoundationLocationService>();
            var uri = new Uri(locationService.ServerAccessMapping.AccessPoint + "/" + requestContext.ServiceHost.Name);
            TeamFoundationTrace.MethodExit();
            return uri;
        }
    }
}
